package org.dreamwork.tools.network.bridge.client.fx;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;

/**
 * Created by seth.yang on 2018/11/23
 */
public class DialogHelp {
    private static Alert createDialog (Alert.AlertType type, String message) {
        Alert alert = new Alert (type);
        alert.setHeaderText (null);
        alert.setContentText (message);
        alert.getDialogPane ().getStylesheets ().add ("web-ui/css/buttons.css");

        return alert;
    }

    public static void info (String message) {
        if (Platform.isFxApplicationThread ()) {
            showInfo (message);
        } else {
            Platform.runLater (()->showInfo (message));
        }
    }

    private static void showInfo (String message) {
        createDialog (Alert.AlertType.INFORMATION, message).showAndWait ();
    }

    public static Optional<ButtonType> prompt (String message) {
        return createDialog (Alert.AlertType.CONFIRMATION, message).showAndWait ();
    }

    public static Optional<ButtonType> option (String message, ButtonType... buttons) {
        Alert alert = createDialog (Alert.AlertType.CONFIRMATION, message);
        alert.getButtonTypes ().clear ();
        for (ButtonType bt : buttons) {
            alert.getButtonTypes ().add (bt);
        }
        return alert.showAndWait ();
    }

    public static void warn (String message) {
        if (Platform.isFxApplicationThread ()) {
            showWarn (message);
        } else {
            Platform.runLater (()-> showWarn (message));
        }
    }

    private static void showWarn (String message) {
        createDialog (Alert.AlertType.WARNING, message).showAndWait ();
    }

    public static void error (String message) {
        if (Platform.isFxApplicationThread ()) {
            createDialog (Alert.AlertType.ERROR, message).showAndWait ();
        } else {
            Platform.runLater (()->createDialog (Alert.AlertType.ERROR, message).showAndWait ());
        }
    }

    public static void error (String message, Throwable cause) {
        if (Platform.isFxApplicationThread ()) {
            showError (message, cause);
        } else {
            Platform.runLater (()->showError (message, cause));
        }
    }

    private static void showError (String message, Throwable cause) {
        Alert alert = createDialog (Alert.AlertType.ERROR, message);

        StringWriter writer = new StringWriter ();
        PrintWriter pw = new PrintWriter (writer, true);
        cause.printStackTrace (pw);

        TextArea area = new TextArea (writer.getBuffer ().toString ());
        alert.getDialogPane ().setExpandableContent (area);
        alert.showAndWait ();
    }
}